package com.edu.labmanager.controller;


import com.edu.labmanager.common.MyUserDetails;
import com.edu.labmanager.entity.Email;
import com.edu.labmanager.entity.Item;
import com.edu.labmanager.entity.LabAdminManagement;
import com.edu.labmanager.entity.Laboratory;
import com.edu.labmanager.service.*;
import com.edu.labmanager.service.impl.RabbitMQProducer;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import org.springframework.stereotype.Controller;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 物品表，存储实验室中各类物品的详细信息 前端控制器
 * </p>
 *
 * @author author
 * @since 2025-06-16
 */
@Controller
@RequestMapping("/item")
@Slf4j
public class ItemController {

    @Autowired
    private IItemService itemService;
    @Autowired
   private RabbitMQProducer rabbitMQProducer;

    @Autowired
    private ILaboratoryService laboratoryService;

    @Autowired
    private CommonService commonService;
    @Autowired
    private ILabAdminManagementService iLabAdminManagementService;

    // 列表页面
    @GetMapping("/")
    @PreAuthorize("hasRole('admin')")
    public String listItems(Model model, @RequestParam(required = false) Integer laboratoryid,
                            @RequestParam(required = false) Integer status,
                            @RequestParam(required = false) String itemName) {
        List<Item> items = itemService.lambdaQuery()
                .eq(laboratoryid!=null, Item::getLaboratoryId, laboratoryid)
                .eq(status!=null, Item::getStatus, status)
                .like(itemName!=null, Item::getItemName, itemName)
                .list();
        model.addAttribute("items", items);
        Map<Integer, String> labmap = laboratoryService.list().stream().collect(Collectors.toMap(Laboratory::getLaboratoryId, Laboratory::getLaboratoryName));
        model.addAttribute("labMap", labmap);
        return "item-list";
    }
    @GetMapping("/add")
    @PreAuthorize("hasRole('admin')")
    public String addItem(Model  model) {
        List<Laboratory> list = laboratoryService.list();
        Map<Integer, String> maplaboratory = list.stream().collect(Collectors.toMap(Laboratory::getLaboratoryId, Laboratory::getLaboratoryName));
        model.addAttribute("mapLaboratory", maplaboratory);
        return "item-add";
    }
    @GetMapping("/update/{itemId}")
    @PreAuthorize("hasRole('admin')")
    public String updateItem(Model model, @PathVariable Integer itemId) {
        Item item = itemService.getById(itemId);
        model.addAttribute("item", item);
        List<Laboratory> list = laboratoryService.list();
        Map<Integer, String> maplaboratory = list.stream().collect(Collectors.toMap(Laboratory::getLaboratoryId, Laboratory::getLaboratoryName));
        model.addAttribute("maplaboratory", maplaboratory);
        return "item-update";
    }
    @PostMapping("/add")
    @PreAuthorize("hasRole('admin')")
    public String addItem(@RequestParam("image") MultipartFile image,
                          @RequestParam("itemname") String itemName,
                          @RequestParam("laboratoryid") Integer laboratoryId,
                          @RequestParam("quantity") Integer quantity,
                          @RequestParam("purchasedate") LocalDateTime purchasedate,
                          @RequestParam("status") Integer  status,
                          @RequestParam("remark") String remark
                         ) throws IOException {
        Item item = new Item();
        if (!image.isEmpty()){
            String upload = commonService.upload(image);
            item.setImage(upload);
        }
        item.setItemName(itemName);
        item.setLaboratoryId(laboratoryId);
        item.setQuantity(quantity);
        item.setPurchaseDate(purchasedate);
        item.setStatus(status);
        item.setRemark(remark);
        itemService.save(item);

        return "redirect:/item/";
    }
    @PostMapping("/update/{id}")
    @PreAuthorize("hasRole('admin')")
    public String updateItem(@RequestParam("image") MultipartFile image,
                          @RequestParam("itemname") String itemName,
                          @RequestParam("laboratoryid") Integer laboratoryId,
                          @RequestParam("quantity") Integer quantity,
                          @RequestParam("purchasedate") LocalDateTime purchasedate,
                          @RequestParam("status") Integer  status,
                          @RequestParam("remark") String remark,
                             Authentication authentication,
                             @PathVariable Integer id) throws IOException {
        Item item = itemService.getById(id);
        if (!image.isEmpty()){
            String upload = commonService.upload(image);
            item.setImage(upload);
        }
        item.setItemName(itemName);
        item.setLaboratoryId(laboratoryId);
        item.setQuantity(quantity);
        item.setPurchaseDate(purchasedate);
        item.setStatus(status);
        item.setRemark(remark);
        itemService.updateById(item);
        if (status == 0){
            Laboratory laboratory = laboratoryService.getById(item.getLaboratoryId());
            MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
            LabAdminManagement labAdminManagement = iLabAdminManagementService.lambdaQuery().eq(LabAdminManagement::getLaboratoryId, laboratoryId).one();
            Email email = new Email();
            email.setUserId(labAdminManagement.getUserId());
            email.setEmail("实验室"+laboratory.getLaboratoryName()+"的"+itemName+"物品已经安排人员前去维修，请检查，无误后及时更新状态");
            email.setSendperson("超级管理员");
            email.setCreatedAt(LocalDateTime.now());
            email.setLabId(laboratoryId);
            rabbitMQProducer.sendEmail(email);
        }
        return "redirect:/item/";
    }



    @GetMapping("/delete/{id}")
    public String deleteItem(@PathVariable Integer id) {
        itemService.removeById(id);
        return "redirect:/item/";
    }
    //员工显示物品信息
    @GetMapping("/list")
    public String list(Model model, Authentication authentication,
                       @RequestParam(required = false) Integer status){
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        Integer userid = userDetails.getId();
        List<LabAdminManagement> list = iLabAdminManagementService.query().eq("user_id", userid).list();
        List<Integer> labIds = list.stream()
                .map(LabAdminManagement::getLaboratoryId)
                .collect(Collectors.toList());

        Map<Integer, String> labmap = laboratoryService.list().stream().collect(Collectors.toMap(Laboratory::getLaboratoryId, Laboratory::getLaboratoryName));
        model.addAttribute("labMap", labmap);

        List<Item> items = itemService.lambdaQuery()
                .eq(status!=null, Item::getStatus, status)
                .in(Item::getLaboratoryId, labIds)
                .list();
        model.addAttribute("items", items);

        return "item-list-by-lab";
    }
    //修改物品状态
    @PostMapping("/update/status/{itemId}/{status}")
    public String updateItemStatus(@PathVariable Integer itemId, @PathVariable Integer status,Authentication authentication) {

       MyUserDetails myUserDetails = (MyUserDetails) authentication.getPrincipal();
        Item item = itemService.getById(itemId);
        Laboratory laboratory = laboratoryService.getById(item.getLaboratoryId());
        if (status==2){
            Email email = new Email();
            email.setUserId(1);
            email.setEmail("实验室"+laboratory.getLaboratoryName()+"的"+item.getItemName()+"物品损坏，请尽快安排人员维修");
            //设置当前时间
            email.setCreatedAt(LocalDateTime.now());
            email.setSendperson(myUserDetails.getUsername());
            email.setLabId(item.getLaboratoryId());
            rabbitMQProducer.sendEmail(email);
        }
        if (status==1){
            item.setRemark("物品正常");
        }
        if (item != null) {
            item.setStatus(status);
            itemService.updateById(item);
        }
        return "redirect:/item/list";
    }
    

}